import * as Sentry from "@sentry/vue";

/**
 * 面包屑管理 Composable
 * 用于统一管理Sentry面包屑的添加和上报
 */
export function useBreadcrumb() {
  /**
   * 添加面包屑到Sentry
   * 支持多个参数，自动拼接和序列化
   * @param args - 任意参数，会被自动转换和拼接
   */
  function addBreadcrumb(...args: any[]) {
    try {
      const message = args
        .map((arg) => {
          if (typeof arg === "object" && arg !== null) {
            try {
              return JSON.stringify(arg);
            } catch (e) {
              return "[对象]";
            }
          }
          return String(arg);
        })
        .join(" ");

      Sentry.addBreadcrumb({
        category: "user_action",
        message: message,
        level: "info",
      });
    } catch (e) {
      // 忽略序列化错误，静默失败
      console.warn("添加面包屑失败:", e);
    }
  }

  /**
   * 添加系统级面包屑
   * @param args - 任意参数
   */
  function addSystemBreadcrumb(...args: any[]) {
    try {
      const message = args
        .map((arg) => {
          if (typeof arg === "object" && arg !== null) {
            try {
              return JSON.stringify(arg);
            } catch (e) {
              return "[对象]";
            }
          }
          return String(arg);
        })
        .join(" ");

      Sentry.addBreadcrumb({
        category: "system",
        message: message,
        level: "info",
      });
    } catch (e) {
      console.warn("添加系统面包屑失败:", e);
    }
  }

  /**
   * 添加错误级面包屑
   * @param args - 任意参数
   */
  function addErrorBreadcrumb(...args: any[]) {
    try {
      const message = args
        .map((arg) => {
          if (typeof arg === "object" && arg !== null) {
            try {
              return JSON.stringify(arg);
            } catch (e) {
              return "[对象]";
            }
          }
          return String(arg);
        })
        .join(" ");

      Sentry.addBreadcrumb({
        category: "error",
        message: message,
        level: "error",
      });
    } catch (e) {
      console.warn("添加错误面包屑失败:", e);
    }
  }

  /**
   * 上报面包屑到Sentry
   * 使用captureMessage触发面包屑数据的上报
   * @param reason - 上报原因
   * @param level - 日志级别，默认为info
   * @param tags - 额外的标签信息
   */
  function reportBreadcrumbs(
    reason: string, 
    level: "info" | "warning" | "error" = "info",
    tags?: Record<string, string>
  ) {
    try {
      addSystemBreadcrumb("上报面包屑", "原因:", reason);
      
      // 使用captureMessage触发面包屑上报
      Sentry.withScope((scope) => {
        // 添加额外的标签
        if (tags) {
          Object.entries(tags).forEach(([key, value]) => {
            scope.setTag(key, value);
          });
        }
        
        // 设置上下文信息
        scope.setContext("breadcrumb_report", {
          reason,
          timestamp: new Date().toISOString(),
          page: "badge_record"
        });
        
        Sentry.captureMessage(`${reason}`, level);
      });
      
      console.log("面包屑已上报:", reason);
    } catch (error) {
      console.error("面包屑上报失败:", error);
    }
  }

  /**
   * 快速上报错误场景
   * @param error - 错误信息
   * @param context - 错误上下文
   */
  function reportError(error: string | Error, context?: Record<string, any>) {
    try {
      const errorMessage = error instanceof Error ? error.message : error;
      
      addErrorBreadcrumb("发生错误:", errorMessage);
      
      Sentry.withScope((scope) => {
        if (context) {
          scope.setContext("error_context", context);
        }
        
        if (error instanceof Error) {
          Sentry.captureException(error);
        } else {
          Sentry.captureMessage(errorMessage, "error");
        }
      });
      
    } catch (e) {
      console.error("错误上报失败:", e);
    }
  }

  /**
   * 页面生命周期面包屑管理
   */
  function setupPageLifecycle(pageName: string, params?: Record<string, any>) {
    // 页面进入
    addBreadcrumb("页面进入:", pageName);
    if (params) {
      addBreadcrumb("页面参数:", params);
    }

    // 监听页面卸载事件
    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      addSystemBreadcrumb("页面即将卸载（浏览器刷新/关闭）");
      reportBreadcrumbs("页面意外卸载", "warning", { page: pageName });
    };

    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        addSystemBreadcrumb("页面变为隐藏状态");
        reportBreadcrumbs("页面隐藏", "info", { page: pageName });
      } else {
        addSystemBreadcrumb("页面重新显示");
      }
    };

    // 添加事件监听器
    window.addEventListener('beforeunload', handleBeforeUnload);
    document.addEventListener('visibilitychange', handleVisibilityChange);

    // 返回清理函数
    return () => {
      addSystemBreadcrumb("清理页面生命周期监听器");
      window.removeEventListener('beforeunload', handleBeforeUnload);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }

  return {
    addBreadcrumb,
    addSystemBreadcrumb,
    addErrorBreadcrumb,
    reportBreadcrumbs,
    reportError,
    setupPageLifecycle
  };
} 